//
//  LGBloodPressureChart.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/3/3.
//  血压统计图

#import "LGBloodPressureChart.h"
#import "LGScrollView.h"
#define topMargin    viewPix(50)

#define leftMargin   viewPix(35)+iPadMargin(10)

#define lineHeight   viewPix(35)

#define scrollWidth    (Screen_W - viewPix(83))

#define scrollHeight (lineHeight*6+viewPix(20))

@interface LGBloodPressureChart()<UIScrollViewDelegate>
/**   */
@property (nonatomic , strong)UILabel *titleLabel;

/**   */
@property (nonatomic , strong)UILabel *dayLabel;
/**   */
@property (nonatomic , strong)UILabel *unitLabel;
/**   */
@property (nonatomic , strong)LGScrollView *scrollView;
/**   */
@property (nonatomic , strong)UIButton *highButton;
/**   */
@property (nonatomic , strong)UIButton *lowButton;

/**   */
@property (nonatomic , strong)UILabel *yaxis140;

/**   */
@property (nonatomic , strong)UILabel *yaxis90;

/**   */
@property (nonatomic , strong)UIView *line140;

/**   */
@property (nonatomic , strong)UIView *line90;

/**   */
@property (nonatomic , strong)NSArray *dayArray;
/**   */
@property (nonatomic , strong)NSArray *highArray;
/**   */
@property (nonatomic , strong)NSArray *lowArray;

/**   */
@property (nonatomic , assign)NSInteger totalCount;
/**   */
@property (nonatomic , assign)CGFloat itemWidth;
@end

@implementation LGBloodPressureChart

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.itemWidth = scrollWidth/7.0;
        [self createSubView];
    }
    return self;
}

-(void)setDataDic:(NSDictionary *)dataDic{
    _dataDic = dataDic;
    if ([dataDic isKindOfClass:[NSDictionary class]] && dataDic.allKeys.count>0) {
        self.totalCount = [dataDic[@"xAxis"] count]>0?[dataDic[@"xAxis"] count]:1;
        NSInteger count = (self.totalCount>7)?7:self.totalCount;
        self.itemWidth = scrollWidth/count;
        CGFloat totalWidth = viewPix(20)+self.itemWidth*self.totalCount;
        self.scrollView.contentSize = CGSizeMake(totalWidth, scrollHeight);
        [self.scrollView setContentOffset:CGPointMake(totalWidth-scrollWidth-viewPix(10), 0)];
        self.dayArray = dataDic[@"xAxis"];
        self.highArray = dataDic[@"seriesSbp"];
        self.lowArray = dataDic[@"seriesDbp"];
    }
}

//创建X轴坐标
-(void)setDayArray:(NSArray *)dayArray{
    _dayArray = dayArray;
    for (NSInteger i=0; i<dayArray.count; i++) {
        NSArray *tempArray = [LGNSString(dayArray[i]) componentsSeparatedByString:@"-"];
        NSString *dayString = [NSString stringWithFormat:@"%@/%@",tempArray[tempArray.count-2],tempArray[tempArray.count-1]];
        UILabel *dayLabel = [UILabel lableWithText:dayString colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        dayLabel.frame = CGRectMake(viewPix(10)+self.itemWidth*i, lineHeight*5.5, self.itemWidth, lineHeight);
        dayLabel.tag = 1000+i;
        [self.scrollView addSubview:dayLabel];
    }
}

//高压曲线
-(void)setHighArray:(NSArray *)highArray{
    _highArray = highArray;
    NSMutableArray *pointArray = [NSMutableArray array];
    for (NSInteger i=0; i<highArray.count; i++) {
        CGFloat pointY = scrollHeight-(([highArray[i][@"value"] floatValue]-40)/40.0*lineHeight+viewPix(20)+lineHeight*0.5);
        UIButton *button = [UIButton buttonWithImage:@"血压-高压Normal" selectImage:@"血压-高压Select"];
        button.bounds = CGRectMake(0, 0, viewPix(20), viewPix(20));
        button.center = CGPointMake(viewPix(10)+self.itemWidth/2.0+self.itemWidth*i, pointY);
        button.tag = 2000+i;
        [button addTarget:self action:@selector(pointButtonTouch:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:button];
        NSValue *point = [NSValue valueWithCGPoint:button.center];
        [pointArray addObject:point];
    }
    [self drawCurveLine:pointArray lineColor:@"#81D899"];
}

//低压曲线
-(void)setLowArray:(NSArray *)lowArray{
    _lowArray = lowArray;
    NSMutableArray *pointArray = [NSMutableArray array];
    for (NSInteger i=0; i<lowArray.count; i++) {
        CGFloat pointY = scrollHeight-(([lowArray[i][@"value"] floatValue]-40)/40.0*lineHeight+viewPix(20)+lineHeight*0.5);
        UIButton *button = [UIButton buttonWithImage:@"血压-低压Normal" selectImage:@"血压-低压Select"];
        button.bounds = CGRectMake(0, 0, viewPix(20), viewPix(20));
        button.center = CGPointMake(viewPix(10)+self.itemWidth/2.0+self.itemWidth*i, pointY);
        button.tag = 3000+i;
        [button addTarget:self action:@selector(pointButtonTouch:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:button];
        NSValue *point = [NSValue valueWithCGPoint:button.center];
        [pointArray addObject:point];
    }
    [self drawCurveLine:pointArray lineColor:@"#429BFF"];
}


-(void)pointButtonTouch:(UIButton *)sender{
    NSInteger index = sender.tag%1000;
    for(NSInteger i=0; i<self.totalCount; i++){
        UIButton *highBtn = [self viewWithTag:2000+i];
        UIButton *lowBtn = [self viewWithTag:3000+i];
        highBtn.selected = (index == i)?YES:NO;
        lowBtn.selected = (index == i)?YES:NO;
    }
    NSDictionary *highDic = @{@"title":@"高压",@"score":LGNSString(self.highArray[index][@"value"]),@"status":LGNSString(self.highArray[index][@"status"])};
    NSDictionary *lowDic = @{@"title":@"低压",@"score":LGNSString(self.lowArray[index][@"value"]),@"status":LGNSString(self.lowArray[index][@"status"])};
    NSArray *tempArray = @[highDic,lowDic];
    CGPoint point = [self.scrollView convertPoint:sender.center toView:self.superview];

    NSLog(@">>>???>>>%f--%f",point.x,point.y);
    if(self.delegate && [self.delegate respondsToSelector:@selector(showAlertView:date:point:)]){
        [self.delegate showAlertView:tempArray date:self.dayArray[index] point:point];
    }
    
    CGPoint point2 = [self.scrollView convertPoint:sender.center toView:self.superview.superview.superview];
    if(self.delegate && [self.delegate respondsToSelector:@selector(showAlertView2:date:point:)]){
        [self.delegate showAlertView2:tempArray date:self.dayArray[index] point:point2];
    }
}


//画线
-(void)drawCurveLine:(NSArray *)arry lineColor:(NSString *)color{
    if(arry.count == 0) return;
    CGPoint startPoint = [[arry objectAtIndex:0] CGPointValue];
    CGPoint lastPoint;
    UIBezierPath *lineBeizer = [UIBezierPath bezierPath];
    [lineBeizer setLineWidth:2.0];
    [lineBeizer moveToPoint:startPoint];

    for (NSInteger i = 0;i < arry.count;i++ ) {
        if (i <arry.count-1 ) {
            CGPoint nowPoint = [[arry objectAtIndex:i] CGPointValue];
            CGPoint futPoint  = [[arry objectAtIndex:i+1] CGPointValue];
            [lineBeizer addCurveToPoint:futPoint controlPoint1:CGPointMake((nowPoint.x+futPoint.x)/2, nowPoint.y) controlPoint2:CGPointMake((nowPoint.x+futPoint.x)/2, futPoint.y)];
            if (i == arry.count-2) {
                [lineBeizer moveToPoint:futPoint];//添加连线
                lastPoint = futPoint;
            }
        }
    }
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = lineBeizer.CGPath;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = [UIColor colorWithString:color].CGColor;
    shapeLayer.lineWidth = 2.0;
    [self.scrollView.layer addSublayer:shapeLayer];
    for(NSInteger i=0; i<self.totalCount; i++){
        UIButton *highBtn = [self viewWithTag:2000+i];
        UIButton *lowBtn = [self viewWithTag:3000+i];
        [self.scrollView bringSubviewToFront:highBtn];
        [self.scrollView bringSubviewToFront:lowBtn];
    }
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if(self.delegate && [self.delegate respondsToSelector:@selector(chartViewTouchesBegan)]){
        [self.delegate chartViewTouchesBegan];
    }
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if(self.delegate && [self.delegate respondsToSelector:@selector(chartViewTouchesBegan)]){
        [self.delegate chartViewTouchesBegan];
    }
}

-(void)createSubView{
    self.backgroundColor = [UIColor clearColor];
    [self addSubview:self.titleLabel];
    [self addSubview:self.baseView];
    [self addSubview:self.titleBtn];
    [self.baseView addSubview:self.dayLabel];
    [self.baseView addSubview:self.scrollView];
    [self.baseView addSubview:self.unitLabel];
    [self.baseView addSubview:self.highButton];
    [self.baseView addSubview:self.lowButton];
    NSArray *titleArray = @[@"240",@"200",@"160",@"120",@"",@"40"];
    for (NSInteger i=0; i<titleArray.count; i++) {
        //Y轴标题
        UILabel *label = [UILabel lableWithText:titleArray[i] colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        label.frame = CGRectMake(0, topMargin+lineHeight*i, leftMargin, lineHeight);
        [self.baseView addSubview:label];
        //虚线
        LGDottedLineView *lineView = [[LGDottedLineView alloc]initWithFrame:CGRectMake(0, lineHeight*i, self.itemWidth*30+viewPix(50), lineHeight)];
        [self.scrollView addSubview:lineView];
    }
    [self.baseView addSubview:self.yaxis140];
    [self.baseView addSubview:self.yaxis90];
    [self.scrollView addSubview:self.line140];
    [self.scrollView addSubview:self.line90];
    [self.titleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.baseView.mas_top).offset(12);
        make.left.right.equalTo(self.baseView);
        make.height.equalTo(@(viewPix(40)));
    }];
}




-(UILabel *)titleLabel{
    if(!_titleLabel){
        _titleLabel = [UILabel lableWithText:@"变化趋势" colorString:@"#333333" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
        _titleLabel.frame = CGRectMake(viewPix(20), viewPix(7), viewPix(100), viewPix(23));
    }
    return _titleLabel;
}

-(UIView *)baseView{
    if(!_baseView){
        _baseView = [[UIView alloc] initWithFrame:CGRectMake(viewPix(16), kMaxY(self.titleLabel.frame)+viewPix(12), Screen_W-viewPix(32), scrollHeight+topMargin+viewPix(35))];
        _baseView.backgroundColor = [UIColor whiteColor];
        _baseView.cornerRidus = 10;
    }
    return _baseView;
}

-(UIButton *)titleBtn{
    if(!_titleBtn){
        _titleBtn = [UIButton buttonWithTitle:@"血压" titleFont:LGFontWeight(16, UIFontWeightMedium) textColor:@"#282828" frame:CGRectMake(0, kMinY(self.baseView.frame), Screen_W-viewPix(32), viewPix(40))];
        _titleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _titleBtn.titleEdgeInsets = UIEdgeInsetsMake(0, viewPix(12), 0, 0);
        _titleBtn.backgroundColor = [UIColor whiteColor];
        _titleBtn.cornerRidus = 10;
        _titleBtn.hidden = YES;
        UIImageView *tipView = [[UIImageView alloc]initWithFrame:CGRectMake(Screen_W-viewPix(32)-viewPix(28), viewPix(12), viewPix(16), viewPix(16))];
        tipView.image = [UIImage imageNamed:@"grayTip16"];
        [_titleBtn addSubview:tipView];
    }
    return _titleBtn;
}


-(UILabel *)dayLabel{
    if(!_dayLabel){
        _dayLabel = [UILabel lableWithText:@"最近30天血压分布" colorString:@"#333333" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft lines:1];
        _dayLabel.frame = CGRectMake(viewPix(12), viewPix(14), viewPix(200), viewPix(23));
    }
    return _dayLabel;
}

-(LGScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[LGScrollView alloc] initWithFrame:CGRectMake(leftMargin, topMargin, scrollWidth, scrollHeight)];
        _scrollView.contentSize = CGSizeMake(self.itemWidth*30+viewPix(20), scrollHeight);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
    }
    return _scrollView;
}

-(UILabel *)unitLabel{
    if(!_unitLabel){
        _unitLabel = [UILabel lableWithText:@"mmHg" colorString:@"#666666" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        _unitLabel.frame = CGRectMake(3, topMargin-6, 50, viewPix(17));
    }
    return _unitLabel;
}

-(UILabel *)yaxis140{
    if(!_yaxis140){
        _yaxis140 = [UILabel lableWithText:@"140" colorString:@"#81D899" textFont:LGFontWeight(12, UIFontWeightMedium) textAlignment:NSTextAlignmentCenter lines:1];
        _yaxis140.frame = CGRectMake(0, topMargin+lineHeight*2.5, leftMargin, lineHeight);
    }
    return _yaxis140;
}

-(UIView *)line140{
    if(!_line140){
        _line140 = [[UIView alloc] initWithFrame:CGRectMake(0, lineHeight*3, self.itemWidth*30+viewPix(50), lineHeight*1.25)];
        _line140.backgroundColor = [UIColor colorWithString:@"#81D899" alpha:0.3];
        UIView *line = [[UIView alloc]init];
        line.backgroundColor = [UIColor colorWithString:@"#81D899"];
        [_line140 addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.line140);
            make.height.equalTo(@(1));
        }];
    }
    return _line140;
}

-(UILabel *)yaxis90{
    if(!_yaxis90){
        _yaxis90 = [UILabel lableWithText:@"90" colorString:@"#429BFF" textFont:LGFontWeight(12, UIFontWeightMedium) textAlignment:NSTextAlignmentCenter lines:1];
        _yaxis90.frame = CGRectMake(0, topMargin+lineHeight*3.75, leftMargin, lineHeight);
    }
    return _yaxis90;
}

-(UIView *)line90{
    if(!_line90){
        _line90 = [[UIView alloc] initWithFrame:CGRectMake(0, lineHeight*4.25, self.itemWidth*30+viewPix(50), lineHeight*0.75)];
        _line90.backgroundColor = [UIColor colorWithString:@"#429BFF" alpha:0.3];
        UIView *line = [[UIView alloc]init];
        line.backgroundColor = [UIColor colorWithString:@"#429BFF"];
        [_line90 addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(self.line90);
            make.height.equalTo(@(1));
        }];
    }
    return _line90;
}

-(UIButton *)highButton{
    if(!_highButton){
        _highButton = [UIButton buttonWithTitle:@" 高压（收缩压）" titleFont:LGFont(15) textColor:@"#333333" imageName:@"血压-高压"];
        _highButton.frame = CGRectMake(0, kMaxY(self.scrollView.frame), (Screen_W-viewPix(32))/2.0-viewPix(10), viewPix(20));
        _highButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    }
    return _highButton;
}

-(UIButton *)lowButton{
    if(!_lowButton){
        CGFloat margin = (Screen_W-viewPix(64)-viewPix(122)*2-viewPix(45)-iPadMargin(50)*3)/2.0;
        _lowButton = [UIButton buttonWithTitle:@" 低压（舒张压）" titleFont:LGFont(15) textColor:@"#333333" imageName:@"血压-低压"];
        _lowButton.frame = CGRectMake(kMaxX(self.highButton.frame)+viewPix(20), kMinY(self.highButton.frame), (Screen_W-viewPix(32))/2.0-viewPix(10), viewPix(20));
        _lowButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    }
    return _lowButton;
}



@end
